package nju.jun.reader.tieba;

import java.util.HashMap;

public class NumberUtils {

//	public static final String[] CHINESE_NUMBER = { "零", "一", "二", "三", "四",
//			"五", "六", "七", "八", "九", "十", "百", "千" };

	private static HashMap C_2_D_MAP;

	static {
		C_2_D_MAP = new HashMap();
		C_2_D_MAP.put('零', 0);
		C_2_D_MAP.put('一', 1);
		C_2_D_MAP.put('二', 2);
		C_2_D_MAP.put('两', 2);
		C_2_D_MAP.put('三', 3);
		C_2_D_MAP.put('四', 4);
		C_2_D_MAP.put('五', 5);
		C_2_D_MAP.put('六', 6);
		C_2_D_MAP.put('七', 7);
		C_2_D_MAP.put('八', 8);
		C_2_D_MAP.put('九', 9);
		C_2_D_MAP.put('十', 10);
		C_2_D_MAP.put('百', 100);
		C_2_D_MAP.put('千', 1000);
		C_2_D_MAP.put('万', 10000);
		C_2_D_MAP.put('亿', 100000000);
	}

	/**
	 * 
	 * @param s
	 * @return 
	 * @throws Exception
	 */
	public static int getNumberFromChineseString(String s) throws Exception {
		if (null == s) {
			throw new Exception("input string cannot be null");
		}
		int rtn = 0;
//		String temp = s;
		int digit = 0;
//		while (temp.length() > 0) {
//			try {
//				digit = getFirstDigit(temp);
//				temp = temp.substring(CHINESE_NUMBER[digit].length());
//				if (digit < 10) {
//					rtn = rtn * 10 + digit;
//				}
//			} catch (Exception e) {
//				throw e;
//			}
//		}
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			digit = getDigit(c);
			if (digit < 10) {
				rtn = rtn * 10 + digit;
			}
		}
		if (digit >= 10) {
			if (Integer.MAX_VALUE / digit < rtn) {
				throw new Exception("Overflow: " + s);
			}
			rtn *= digit;
		}
		return rtn;
	}
	
	private static int getDigit(char c) throws Exception {
		if (C_2_D_MAP.containsKey(c)) {
			return (Integer) C_2_D_MAP.get(c);
		}
		throw new Exception("Char " + c + " cannot be converted to int.");
	}

//	private static int getFirstDigit(String s) throws Exception {
//		for (int i = 0; i < CHINESE_NUMBER.length; i++) {
//			if (s.startsWith(CHINESE_NUMBER[i])) {
//				return i;
//			}
//		}
//
//		throw new Exception("String cannot be converted to int: " + s);
//	}

	public static void main(String[] args) {
		String t1 = "六十";
		String t2 = "一百";
		String t3 = "一千两百八十";
		String t4 = "一千";
		String t5 = "一千一百";
		String t6 = "一千一百四十八";
		try {
			System.out.println(NumberUtils.getNumberFromChineseString(t1));
			System.out.println(NumberUtils.getNumberFromChineseString(t2));
			System.out.println(NumberUtils.getNumberFromChineseString(t3));
			System.out.println(NumberUtils.getNumberFromChineseString(t4));
			System.out.println(NumberUtils.getNumberFromChineseString(t5));
			System.out.println(NumberUtils.getNumberFromChineseString(t6));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
